package cn.jhz.learn.blog.service.security.permission.impl;

import cn.jhz.learn.blog.dao.account.AccountPermissionMapper;
import cn.jhz.learn.blog.dao.account.AccountRolePermissionMapper;
import cn.jhz.learn.blog.po.account.AccountPermission;
import cn.jhz.learn.blog.po.account.AccountRole;
import cn.jhz.learn.blog.service.security.permission.PermissionService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {

    private final AccountPermissionMapper permissionMapper;
    private final AccountRolePermissionMapper rolePermissionMapper;

    @Autowired
    public PermissionServiceImpl(AccountPermissionMapper permissionMapper, AccountRolePermissionMapper rolePermissionMapper) {
        this.permissionMapper = permissionMapper;
        this.rolePermissionMapper = rolePermissionMapper;
    }

    @Override
    public List<String> getAllPermission() {
        return permissionMapper.selectAllResources();
    }

    @Override
    public void addPermission(List<AccountPermission> permissions){
        if(permissions.size() > 0)
            permissionMapper.batchInsertResource(permissions);
    }

    @Override
    public Set<String> getPermissionResourceByRoles(Set<AccountRole> roles) {
        Set<String> permissions = Sets.newConcurrentHashSet();
        if(roles.size() > 0){
            List<Integer> permissionIds = rolePermissionMapper.selectPermissionIdsByRoleIds(
                    roles.stream().map(AccountRole::getId).collect(Collectors.toList())
            );
            if(permissionIds.size() > 0)
                permissions.addAll(permissionMapper.selectResourceByPrimaryKeys(permissionIds));
        }

        return permissions;
    }
}
